package com.example.yifei.ui.page.widgets

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.example.yifei.R
import com.example.yifei.ui.page.common.BottomNavRoute
import com.example.yifei.ui.theme.SearchBarHeight
import com.example.yifei.ui.theme.TabBarHeight
import com.example.yifei.ui.theme.ToolBarHeight
import com.google.accompanist.placeholder.material.placeholder
import com.google.accompanist.systemuicontroller.rememberSystemUiController

/**
 * 普通标题栏头部
 */
@Composable
fun AppToolsBar(
    title: String,
    color: Color = Color.White,
    fontSize: TextUnit = 17.sp,
    painter: Painter = painterResource(id = R.mipmap.back),
    onBack: (() -> Unit)? = null,
    modifier: Modifier = Modifier
        .fillMaxWidth()
        .padding(start = 17.dp, top = 54.dp),
) {
    Box(
        modifier = modifier
    ) {

        if (onBack != null) {
            Image(
                painter = painter,
                contentDescription = "返回",
                modifier = Modifier
                    .height(20.dp)
                    .clickable {
                        onBack()
                    }
            )

        }

        Text(
            text = title,
            modifier = Modifier
                .align(Alignment.Center),
            color = color,
            textAlign = TextAlign.Center,
            fontSize = fontSize,
            fontWeight = FontWeight.W500,
            maxLines = 1
        )

    }
}


/**
 * author ：Peakmain
 * createTime：2022/5/4
 * mail:2726449200@qq.com
 * describe：
 */

/**
 * @param title 标题
 * @param modifier Modifier，设置后会和已经设置好Modifier进行合并
 * @param navigationIcon 左边图标
 * @param backgroundColor 背景颜色
 * @param actions 右边图标
 * @param isImmersive 是否是沉浸式
 * @param darkIcons 状态栏的文字图标颜色是黑色还是白色，默认是false（白色）
 * @param content 内容区域
 */
@Composable
fun TopAppBarCenter(
    title: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    navigationIcon: @Composable (() -> Unit)? = null,
    backgroundColor: Color = MaterialTheme.colors.primarySurface,
    actions: @Composable RowScope.() -> Unit = {},
    isImmersive: Boolean = false,
    darkIcons: Boolean = false,
    content: @Composable (PaddingValues) -> Unit,
) {
    val topAppBarHeight = 56.dp
    var statusBarHeight = 0
    var statusBarHeightDp = Dp(0f)
    if (isImmersive) {
        val systemUiController = rememberSystemUiController()
        SideEffect {
            systemUiController.setSystemBarsColor(
                color = Color.Transparent,
                darkIcons = darkIcons
            )
        }
        with(LocalContext.current) {
            statusBarHeight =
                resources.getDimensionPixelSize(
                    resources.getIdentifier(
                        "status_bar_height",
                        "dimen",
                        "android"
                    )
                )
        }
        with(LocalDensity.current) {
            statusBarHeightDp = statusBarHeight.toDp()
        }
    }

    Scaffold(topBar = {
        val constraintSet = ConstraintSet {
            val titleRef = createRefFor("title")
            val navigationIconRef = createRefFor("navigationIcon")
            val actionsRef = createRefFor("actions")
            constrain(titleRef) {
                start.linkTo(parent.start)
                end.linkTo(parent.end)
                top.linkTo(parent.top)
                bottom.linkTo(parent.bottom)
            }
            constrain(navigationIconRef) {
                top.linkTo(parent.top)
                bottom.linkTo(parent.bottom)
            }
            constrain(actionsRef) {
                top.linkTo(parent.top)
                bottom.linkTo(parent.bottom)
                end.linkTo(parent.end)
            }
        }
        ConstraintLayout(
            constraintSet, modifier = Modifier
                .fillMaxWidth()
                .background(backgroundColor)
                .then(modifier)
                .height(topAppBarHeight + statusBarHeightDp)
                .padding(top = statusBarHeightDp)
        ) {
            Box(
                Modifier
                    .layoutId("title")
                    .padding(horizontal = 4.dp)
            ) {
                ProvideTextStyle(value = MaterialTheme.typography.h6) {
                    CompositionLocalProvider(
                        LocalContentAlpha provides ContentAlpha.high,
                        content = title
                    )
                }
            }
            if (navigationIcon != null) {
                Box(
                    modifier = Modifier
                        .layoutId("navigationIcon")
                        .padding(start = 4.dp)
                ) {
                    CompositionLocalProvider(
                        LocalContentAlpha provides ContentAlpha.high,
                        content = navigationIcon
                    )
                }
            }
            Row(
                Modifier
                    .layoutId("actions")
                    .padding(end = 4.dp),
                content = actions
            )

        }
    }) {
        content(it)
    }

}

@Composable
fun HomeSearchBar(
    onSearchClick: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(SearchBarHeight)
            .background(color = Color.White)
    ) {
        Row(
            modifier = Modifier
                .padding(horizontal = 32.dp)
                .height(30.dp)
                .align(alignment = Alignment.Top)
                .weight(1f)
                .background(
                    color = Color(0xFFFFFFFF),
                    shape = RoundedCornerShape(12.5.dp)
                )
                .clickable { onSearchClick() }
        ) {
            Icon(
                painter = painterResource(id = com.example.yifei.R.drawable.ic_search),
                contentDescription = "搜索",
                tint = Color(0xFF1E1E1E),
                modifier = Modifier
                    .size(25.dp)
                    .padding(start = 10.dp)
                    .align(Alignment.CenterVertically)
            )
            Box(
                modifier = Modifier
                    .weight(1f)
                    .align(Alignment.CenterVertically)
                    .padding(start = 10.dp)
            ) {
                Text(text = "搜索关键词以空格形式隔开", fontSize = 13.sp, color = Color(0xFF888888))
            }
        }
    }
}


/**
 * TabLayout
 */
@Composable
fun TextTabBar(
    index: Int,
    tabTexts: List<TabTitle>,
    modifier: Modifier = Modifier
        .fillMaxWidth()
        .height(44.dp)
        .background(Color.White),
    horizontalArrangement: Arrangement.Horizontal = if (tabTexts.size > 4) Arrangement.SpaceEvenly else Arrangement.SpaceAround,
    contentColor: Color = Color(0Xff336AF8),
    unContentColor: Color = Color(0Xff373C55),
    indicatorColor: Color = Color(0Xff336AF8),
    unIndicatorColor: Color = Color.White,
    fontSize: TextUnit = 14.sp,
    onTabSelected: ((index: Int) -> Unit)? = null
) {
    LazyRow(
        modifier = modifier,
        horizontalArrangement = horizontalArrangement,
        verticalAlignment = Alignment.Bottom
    ) {

        itemsIndexed(tabTexts) { i, tabTitle ->
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = tabTitle.text,
                    fontSize = fontSize,
                    fontWeight = if (index == i) FontWeight.SemiBold else FontWeight.Normal,
                    modifier = Modifier
                        .pointerInput(Unit) {
                            detectTapGestures(onTap = {
                                onTabSelected?.invoke(i)
                            })
                        },
                    color = if (index == i) contentColor else unContentColor
                )

                Spacer(
                    modifier = Modifier
                        .height(8.dp)
                )

                Spacer(
                    modifier = Modifier
                        .width(14.dp)
                        .height(3.dp)
                        .background(
                            color = if (index == i) indicatorColor else unIndicatorColor,
                            shape = RoundedCornerShape(4.dp)
                        )
                )

            }
        }
//        tabTexts.forEachIndexed { i, tabTitle ->
//            Column(
//                horizontalAlignment = Alignment.CenterHorizontally
//            ) {
//                Text(
//                    text = tabTitle.text,
//                    fontSize = fontSize,
//                    fontWeight = if (index == i) FontWeight.SemiBold else FontWeight.Normal,
//                    modifier = Modifier
//                        .pointerInput(Unit) {
//                            detectTapGestures(onTap = {
//                                onTabSelected?.invoke(i)
//                            })
//                        },
//                    color = if (index == i) contentColor else unContentColor
//                )
//
//                Spacer(
//                    modifier = Modifier
//                        .height(8.dp)
//                )
//
//                Spacer(
//                    modifier = Modifier
//                        .width(14.dp)
//                        .height(3.dp)
//                        .background(
//                            color = if (index == i) indicatorColor else unIndicatorColor,
//                            shape = RoundedCornerShape(4.dp)
//                        )
//                )
//
//            }
//
//
//        }
    }

}

data class TabTitle(
    val id: Int,
    val text: String,
    var cachePosition: Int = 0,
    var selected: Boolean = false
)


@Composable
fun TabBar(
    index: Int = 0,
    tabTexts: List<String>,
    modifier: Modifier = Modifier,
    bgColor: Color,
    contentColor: Color,
    onTabSelected: ((index: Int) -> Unit)?,
    isScrollable: Boolean = true
) {
    if (isScrollable) {
        ScrollableTabRow(
            selectedTabIndex = index,
            modifier = modifier.height(TabBarHeight),
            edgePadding = 0.dp,
            backgroundColor = bgColor,
            contentColor = contentColor,
        ) {
            //var offset: Float by remember { mutableStateOf(0f) }
            tabTexts.forEachIndexed { i, tabText ->
                Text(
                    text = tabText,
                    fontSize = if (index == i) 20.sp else 15.sp,
                    fontWeight = if (index == i) FontWeight.SemiBold else FontWeight.Normal,
                    modifier = Modifier
                        .padding(horizontal = 10.dp)
                        .clickable {
                            if (onTabSelected != null) {
                                onTabSelected(i)
                            }
                        },
                    color = contentColor
                )
            }
        }
    } else {
        TabRow(
            selectedTabIndex = index,
            modifier = modifier.height(TabBarHeight),
            backgroundColor = bgColor,
            contentColor = contentColor,
        ) {
            tabTexts.forEachIndexed { i, tabText ->
                Text(
                    text = tabText,
                    fontSize = if (index == i) 20.sp else 15.sp,
                    fontWeight = if (index == i) FontWeight.SemiBold else FontWeight.Normal,
                    modifier = Modifier
                        .padding(horizontal = 10.dp)
                        .clickable {
                            if (onTabSelected != null) {
                                onTabSelected(i)
                            }
                        },
                    color = contentColor
                )
            }
        }
    }
}


/**
 * 底部导航样式
 */
@Composable
fun BottomNavBarView(navCtrl: NavHostController) {
    val bottomNavList = listOf(
        BottomNavRoute.Home,
        BottomNavRoute.ProductionDemand,
        BottomNavRoute.Collection,
        BottomNavRoute.PurchaseList,
        BottomNavRoute.Profile
    )
    BottomNavigation(backgroundColor = Color.White) {
        val navBackStackEntry by navCtrl.currentBackStackEntryAsState()
        val currentDestination = navBackStackEntry?.destination

        bottomNavList.forEach { screen ->
            val selected =
                currentDestination?.hierarchy?.any { it.route == screen.routeName } == true
            val painter: Int
            val color: Long

            if (selected) {
                painter = screen.icon
                color = 0xff336AF8
            } else {
                painter = screen.iconNor
                color = 0xff373C55
            }
            BottomNavigationItem(
                selected = selected,

                icon = {
                    Image(painter = painterResource(painter), contentDescription = "")
                },

                label = {
                    Text(
                        text = stringResource(screen.stringId),
                        color = Color(color),
                        fontSize = 12.sp
                    )
                },

                onClick = {
                    println("BottomNavView当前路由 ===> ${currentDestination?.hierarchy?.toList()}")
                    println("当前路由栈 ===> ${navCtrl.graph.nodes}")
                    if (currentDestination?.route != screen.routeName) {
                        navCtrl.navigate(screen.routeName) {
                            popUpTo(navCtrl.graph.findStartDestination().id) {
                                saveState = true
                            }
                            launchSingleTop = true
                            restoreState = true
                        }
                    }
                })
        }
    }
}


@Composable
fun EmptyView(
    tips: String = "啥都没有~",
    imageVector: ImageVector = Icons.Default.Info,
    onClick: () -> Unit = {}
) {
    Box(
        modifier = Modifier
            .fillMaxSize(1f)
            .defaultMinSize(minHeight = 480.dp)
    ) {
        Column(
            Modifier
                .wrapContentSize()
                .align(Alignment.Center)
                .clickable { onClick.invoke() }
        ) {
            Icon(
                imageVector = imageVector,
                contentDescription = null,
                tint = Color(0xFF888888),
                modifier = Modifier.align(Alignment.CenterHorizontally)
            )
            TextContent(text = tips, modifier = Modifier.padding(top = 10.dp))
        }
    }
}

@Composable
fun SwitchTabBar(
    titles: MutableList<TabTitle>,
    heightValue: Dp? = null,
    selectIndex: Int,
    onSwitchClick: (index: Int) -> Unit
) {

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(heightValue ?: ToolBarHeight)
            .background(color = Color(0xFF1E1E1E))
            .padding(vertical = 5.dp)
    ) {
        Row(
            modifier = Modifier.align(Alignment.Center)
        ) {
            titles.forEachIndexed { index, tabTitle ->
                MediumTitle(
                    title = tabTitle.text,
                    color = if (index == selectIndex) Color(0xFFD5D5D5)
                    else Color(0xFF888888),
                    modifier = Modifier
                        .defaultMinSize(100.dp, 24.dp)
                        .padding(horizontal = 10.dp)
                        .clickable { onSwitchClick.invoke(index) },
                    textAlign = TextAlign.Center
                )
            }
        }
        Box(
            modifier = Modifier
                .width(1.dp)
                .height(16.dp)
                .background(color = Color(0xFF888888))
                .align(Alignment.Center)
        )
    }
}


@Composable
fun TagView(
    modifier: Modifier = Modifier,
    tagText: String,
    tagBgColor: Color = Color(0xFF111111),
    borderColor: Color = Color(0xFF1E1E1E),
    tagTextColor: Color = Color(0xFF888888),
    isLoading: Boolean = false,
) {
    Box(
        modifier = modifier
            .wrapContentSize()
            .background(color = tagBgColor)
            .clip(RoundedCornerShape(2.dp))
            .border(width = 1.dp, color = borderColor)
            .placeholder(
                visible = isLoading,
                color = Color(0xFF888888)
            )
    ) {
        MiniTitle(
            text = tagText,
            color = tagTextColor,
            modifier = Modifier
                .align(Alignment.Center)
                .padding(horizontal = 5.dp, vertical = 0.dp),
        )
    }
}


